import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/constom_tag_selector.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_search_history_notifier.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_topic_search_notifier.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/data/repository/life_repository_impl.dart';

import 'package:casdon/modules/lifeCircle/providers/life_search_providers.dart';
import 'package:casdon/modules/lifeCircle/services/follow_status_sync_service.dart';
import 'package:casdon/modules/lifeCircle/ui/widgets/topic_item_widget.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:casdon/auto_router.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class LifeSearchScreen extends ConsumerStatefulWidget {
  const LifeSearchScreen({super.key});

  @override
  ConsumerState<LifeSearchScreen> createState() => _LifeSearchScreenState();
}

class _LifeSearchScreenState extends ConsumerState<LifeSearchScreen> {
  late TextEditingController keywordController;
  late FocusNode focusNode;
  bool _isRefreshing = false;

  @override
  void initState() {
    super.initState();
    keywordController = TextEditingController();
    focusNode = FocusNode();

    // 自动聚焦搜索框
    WidgetsBinding.instance.addPostFrameCallback((_) {
      focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    keywordController.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final keyword = ref.watch(lifeSearchKeywordProvider);
    final submittedKeyword = ref.watch(lifeSubmittedKeywordProvider);
    final asyncTopics = ref.watch(lifeTopicSearchProvider(submittedKeyword));
    final searchNotifier = ref.watch(
      lifeTopicSearchProvider(submittedKeyword).notifier,
    );
    final tagsState = ref.watch(lifeSearchHistoryProvider);
    final tagsNotifier = ref.watch(lifeSearchHistoryProvider.notifier);

    if (keywordController.text != keyword) {
      keywordController.text = keyword;
      keywordController.selection = TextSelection.fromPosition(
        TextPosition(offset: keywordController.text.length),
      );
    }

    // 判断是否应该显示历史标签（初始状态：未提交搜索且输入框为空）
    final shouldShowHistory = submittedKeyword.isEmpty && keyword.isEmpty;

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(context, ref, searchNotifier),
      body: shouldShowHistory
          ? CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: _buildTagSelector(tagsState, tagsNotifier),
                ),
              ],
            )
          : submittedKeyword.isEmpty
          ? const SizedBox.shrink() // 输入框有内容但未提交，不显示任何内容
          : NotificationListener<ScrollNotification>(
              onNotification: (notification) {
                // 在任何滚动事件中，首先检查刷新状态
                final isRefreshing =
                    _isRefreshing || searchNotifier.isRefreshing;

                // 如果正在刷新，直接返回，不处理任何滚动事件
                if (isRefreshing) {
                  return false;
                }

                // 如果是滚动结束事件且需要加载更多
                if (notification is ScrollEndNotification) {
                  final metrics = notification.metrics;

                  // 检查是否滚动到底部附近
                  // 条件：
                  // 1. pixels > 0：确保是向下滚动（下拉刷新时 pixels 可能是负数）
                  // 2. pixels >= maxScrollExtent - 50：接近或到达底部
                  // 3. extentBefore > 0：确保有内容在前面（防止下拉刷新时误判）
                  // 4. extentAfter < 50：确实接近底部
                  if (metrics.pixels > 0 &&
                      metrics.extentBefore > 0 &&
                      metrics.pixels >= metrics.maxScrollExtent - 50 &&
                      metrics.extentAfter < 50) {
                    // 最后一次检查刷新状态，确保在准备调用 loadMore 时没有开始刷新
                    final finalIsRefreshing =
                        _isRefreshing || searchNotifier.isRefreshing;
                    if (!finalIsRefreshing) {
                      searchNotifier.loadMore();
                    }
                  }
                }
                return false;
              },
              child: RefreshIndicator(
                onRefresh: () async {
                  // 在开始刷新前立即设置标志，防止并发操作
                  if (_isRefreshing) {
                    return;
                  }
                  // 立即设置刷新标志，防止滚动监听器触发 loadMore
                  _isRefreshing = true;
                  try {
                    await searchNotifier.refresh();
                  } finally {
                    // 确保在 finally 中重置，即使出错也要重置
                    _isRefreshing = false;
                  }
                },
                child: CustomScrollView(
                  slivers: [
                    asyncTopics.when(
                      data: (topics) {
                        if (topics.data.isNotEmpty) {
                          tagsNotifier.insertData(submittedKeyword);
                        }

                        if (topics.data.isEmpty) {
                          return SliverFillRemaining(
                            hasScrollBody: false,
                            child: Column(
                              children: [
                                const Spacer(flex: 2),
                                _buildNoDataWidget(),
                                const Spacer(flex: 8),
                              ],
                            ),
                          );
                        }

                        return SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) =>
                                // TopicItemWidget(
                                //   key: ValueKey(
                                //     'search_topic_${topics.data[index].id}_$index',
                                //   ),
                                //   showFollowBtn:
                                //       topics.data[index].isFollow == false &&
                                //       topics.data[index].isMyTopic == false,
                                //   topic: topics.data[index],
                                // ),
                                TopicItemWidget(
                                  key: ValueKey(
                                    'search_topic_${topics.data[index].id}_$index',
                                  ),
                                  topic: topics.data[index],
                                  showFollowBtn:
                                      topics.data[index].isFollow == false &&
                                      topics.data[index].isMyTopic == false,
                                  onCommentTap: () => _handleCommentTap(
                                    context,
                                    topics.data[index].id,
                                  ),
                                  onZanTap: (topic) =>
                                      _handleZanTap(context, topic),
                                  onAvaterTap: () => _handleAvaterTap(
                                    context,
                                    topics.data[index].userId,
                                    topics.data[index].userNickname,
                                    topics.data[index].avatar,
                                  ),
                                  onFollowTap: () => _handleFollowTap(
                                    context,
                                    topics.data[index],
                                  ),
                                  onContentTap: () => _handleCommentTap(
                                    context,
                                    topics.data[index].id,
                                  ),
                                ),
                            childCount: topics.data.length,
                          ),
                        );
                      },
                      loading: () => const SliverToBoxAdapter(
                        child: Center(
                          child: Padding(
                            padding: EdgeInsets.all(16.0),
                            child: CircularProgressIndicator(),
                          ),
                        ),
                      ),
                      error: (err, _) => SliverFillRemaining(
                        hasScrollBody: false,
                        child: Column(
                          children: [
                            const Spacer(flex: 2),
                            _buildNoDataWidget(),
                            const Spacer(flex: 8),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  PreferredSizeWidget _buildAppBar(
    BuildContext context,
    WidgetRef ref,
    LifeTopicSearchNotifier notifier,
  ) {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.white,
      titleSpacing: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new, color: Colors.black87),
        onPressed: () => Navigator.pop(context),
      ),
      title: Container(
        margin: EdgeInsets.only(right: 12.w),
        height: 36.h,
        decoration: BoxDecoration(
          color: const Color(0xFFF2F2F2),
          borderRadius: BorderRadius.circular(18),
        ),
        child: Row(
          children: [
            SizedBox(width: 10.w),
            const Icon(Icons.search, color: Colors.grey),
            SizedBox(width: 6.w),
            Expanded(
              child: TextField(
                controller: keywordController,
                focusNode: focusNode,
                decoration: InputDecoration(
                  hintText: "搜索帖子",
                  hintStyle: context.textTheme.bodyMedium!.copyWith(
                    color: context.customColorThemeNonNull.textColor2,
                  ),
                  border: InputBorder.none,
                  isDense: true,
                ),
                textInputAction: TextInputAction.search,
                onChanged: (value) {
                  ref.read(lifeSearchKeywordProvider.notifier).state = value;
                },
                onSubmitted: (value) {
                  if (value.trim().isNotEmpty) {
                    ref.read(lifeSubmittedKeywordProvider.notifier).state =
                        value.trim();
                  }
                },
              ),
            ),
            if (keywordController.text.isNotEmpty)
              IconButton(
                icon: const Icon(Icons.close, size: 18, color: Colors.grey),
                onPressed: () async {
                  keywordController.clear();
                  ref.read(lifeSearchKeywordProvider.notifier).state = "";
                  await notifier.clearData();
                  focusNode.requestFocus();
                },
              ),
          ],
        ),
      ),
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1),
        child: Container(
          width: double.infinity,
          color: context.customColorThemeNonNull.gray1,
          height: 1,
        ),
      ),
    );
  }

  Widget _buildNoDataWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.noData.provider(),
            width: 80.w,
            height: 80.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "无搜索结果",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTagSelector(
    AsyncValue<List<String>> list,
    LifeSearchHistoryNotifier notifier,
  ) {
    return list.when(
      data: (data) {
        if (data.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(height: 128.h),
                Image(image: Assets.images.logoBg.provider()),
              ],
            ),
          );
        }
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                SizedBox(width: 16.w),
                Text(
                  "最近搜索",
                  style: context.textTheme.bodyLarge!.copyWith(
                    color: context.customColorThemeNonNull.textColor3,
                  ),
                ),
                const Spacer(),
                TextButton(
                  onPressed: () async {
                    await notifier.clear();
                  },
                  child: Text(
                    "清空",
                    style: context.textTheme.bodyMedium!.copyWith(
                      color: context.colorScheme.primary,
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
              ],
            ),
            SizedBox(height: 12.h),
            ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 5 * 42.h),
              child: CustomTagSelector<String>(
                options: data,
                value: [],
                multiChoice: false,
                wrapped: true,
                textStyle: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor3,
                ),
                selectedTextStyle: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor3,
                ),
                normalBgColor: context.customColorThemeNonNull.gray2,
                selectedBgColor: context.customColorThemeNonNull.gray2,
                onChanged: (value) {
                  if (value.isNotEmpty) {
                    final selectedKeyword = value.first;
                    // 只更新输入框内容，不触发搜索
                    ref.read(lifeSearchKeywordProvider.notifier).state =
                        selectedKeyword;
                    // 清除之前的搜索结果
                    ref.read(lifeSubmittedKeywordProvider.notifier).state = "";
                  }
                },
              ),
            ),
            SizedBox(height: 12.h),
          ],
        );
      },
      loading: () => const Center(
        child: Padding(padding: EdgeInsets.all(16.0), child: SizedBox.shrink()),
      ),
      error: (err, _) => const Center(child: SizedBox.shrink()),
    );
  }

  void _handleCommentTap(BuildContext context, String topicId) {
    context.router.push(LifeTopicDetailRoute(topicId: topicId));
  }

  Future<void> _handleZanTap(
    BuildContext context,
    LifeTopicModule topic,
  ) async {
    try {
      final repository = LifeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );

      final isLiked = topic.isLike;
      final currentLikes = topic.likes;

      // 调用点赞接口
      await repository.likeTopic(
        id: topic.id,
        type: 0, // 0-帖子，1-评论
        flag: isLiked ? 0 : 1, // 0-取消点赞，1-点赞
      );

      // // 更新本地状态，避免刷新整个列表
      final newLikesCount = isLiked ? currentLikes - 1 : currentLikes + 1;

      final submittedKeyword = ref.read(lifeSubmittedKeywordProvider);
      if (submittedKeyword.isNotEmpty) {
        ref
            .read(lifeTopicSearchProvider(submittedKeyword).notifier)
            .updateTopicLikeStatus(topic.id, !isLiked, newLikesCount);
      }
    } on DioException catch (e) {
    } catch (e) {
      // 处理错误，可以显示 Toast
      debugPrint("点赞操作失败: $e");
    }
  }

  void _handleAvaterTap(
    BuildContext context,
    String userId,
    String userNickName,
    String avatar,
  ) async {
    final storage = ref.read(authStorageProvider.notifier);
    final uid = await storage.getUserId();
    if (context.mounted == false) return;
    if (uid == userId) {
      context.router.push(const LifeSelfHomeRoute());
      return;
    }
    context.router.push(
      LifeUserHomeRoute(userId: userId, nickName: userNickName, avatar: avatar),
    );
  }

  Future<void> _handleFollowTap(
    BuildContext context,
    LifeTopicModule topic,
  ) async {
    try {
      final repository = MeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );
      final isFollowed = topic.isFollow;
      final newFollowStatus = !isFollowed;

      // 取消关注前弹确认
      if (isFollowed) {
        final confirm = await showCustomConfirmDialog(
          context: context,
          title: '',
          content: '不再关注该作者？',
          confirmText: '不再关注',
          cancelText: '取消',
        );
        if (confirm != true) return;
      }

      await repository.followUser(
        followUuid: topic.userId,
        flag: isFollowed ? "0" : "1", // "1"：关注，"0"：取消关注
      );
      if (isFollowed == false) {
        ToastUtil.show("关注成功");
      } else {
        ToastUtil.show("取消关注成功");
      }
      // 使用统一的同步服务更新所有相关列表的状态
      final syncService = FollowStatusSyncService(ref);
      syncService.syncFollowStatus(topic.userId, newFollowStatus);
    } on DioException catch (e) {
    } catch (e) {
      // 处理错误，可以显示 Toast
      debugPrint("关注操作失败: $e");
      if (context.mounted) {}
    }
  }
}
